package com.xiaren.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 编程式事务
 * @ClassName: DemoService
 * @Auther: Administrator
 * @Date: 2018/12/14 13:53
 * @Version: 0.0.1
 */

@Slf4j
@Service
public class DemoService3 {

    @Autowired
    BookingService bookingService;
    @Autowired
    StudentService studentService;
    @Autowired
    private TransactionTemplate transactionTemplate;

    public static final ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(50);


    public void transactionMySqlDemo(){

        Boolean isSuccess = transactionTemplate.execute(new TransactionCallback<Boolean>() {
            public Boolean doInTransaction(TransactionStatus status) {
                Boolean result = true;
                try {
                    long insert = bookingService.insert("3333");
                    System.out.println(insert);
                    bookingService.insert("4444444444");
                } catch (Exception e) {
                    status.setRollbackOnly();
                    result = false;
                    log.error(e.getMessage(), e);
                }
                return result;
            }
        });

        System.out.println(isSuccess);

    }

    public void transactionMySqlDemo2(String name){
        newFixedThreadPool.execute(() -> {
            transactionTemplate.execute(new TransactionCallback<Boolean>() {
                public Boolean doInTransaction(TransactionStatus status) {
                    Boolean result = true;
                    try {
                        long id = studentService.insert2(name, "0", null);
                        Thread.sleep(50);
                        studentService.update(id, "name" + id);
                    } catch (Exception e) {
                        status.setRollbackOnly();
                        result = false;
                        log.error(e.getMessage(), e);
                    }
                    System.out.println("2完毕");
                    return result;
                }
            });
        });
    }

    public void transactionMySqlDemo3(String name){
        newFixedThreadPool.execute(() -> {
            List<Map<String, Object>> byName = studentService.findByName(name);
            if(!byName.isEmpty()){
                System.out.println(byName);
            }
            System.out.println("33");
        });
    }

}
